package vip.zhenzicheng.concurrent_program.interview.alternate_output_letters;

/**
 * 使用 wait/notify + Synchronize 实现两个线程交替输出字母
 * 问题：怎么保证t1一定先执行？
 * 1. 使用 volatile的boolean + CAS
 * 2. 使用 CountDownLatch
 *
 * @author zhenzicheng
 * @date: 2022-06-02 21:56
 * @see Solution_SyncWaitNotify_CountDownLatch
 */
public class Solution_SyncWaitNotify {
  static Thread t1 = null, t2 = null;

  public static void main(String[] args) {
    char[] s1 = "123456789".toCharArray();
    char[] s2 = "abcdefghi".toCharArray();

    Object o = new Object(); // 创建一个对象用来上锁

    t1 = new Thread(() -> {
      synchronized (o) {
        for (char c : s1) {
          System.out.print(c);
          try {
            o.notify();
            o.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        o.notify(); // 必须唤醒最后一个阻塞的线程，否则将会一直wait
      }
    }, "t1");

    Thread t2 = new Thread(() -> {
      synchronized (o) {
        for (char c : s2) {
          System.out.print(c);
          try {
            o.notify();
            o.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        o.notify();
      }
    }, "t2");

    t1.start();
    t2.start();
  }
}
